/**
 *Copyright (c) 2024 watereyes
 * safetymanagement is licensed under Mulan PubL v2.
 * You can use this software according to the terms and conditions of the Mulan
 * PubL v2.
 * You may obtain a copy of Mulan PubL v2 at:
 *          http://license.coscl.org.cn/MulanPubL-2.0
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PubL v2 for more details.
 */
package com.koron.risk.service.impl;


import com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson;
import com.koron.audit.approval.AfterApprovalService;
import com.koron.audit.domain.Audit;
import com.koron.audit.management.FlowManagement;
import com.koron.common.bean.DepartmentTreeBean;
import com.koron.common.bean.StaffBean;
import com.koron.common.dfs.FastDFSClientWrapper;
import com.koron.common.domain.DataBean;
import com.koron.common.generator.DefaultIdGenerator;
import com.koron.common.web.Util;
import com.koron.hazardsource.util.Immutable;
import com.koron.risk.bean.CorpBean;
import com.koron.risk.domain.LocalCheckListEntry;
import com.koron.risk.domain.LocalCheckListItem;
import com.koron.risk.mapper.CorpManagementMapper;
import com.koron.risk.mapper.LocalCheckListItemMapper;
import com.koron.risk.mapper.LocalCheckListMapper;
import com.koron.risk.service.api.LocalCheckListService;
import com.koron.risk.util.BusinessCode;
import com.koron.system.domain.DictData;
import com.koron.system.service.api.DictDataService;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.koron.ebs.mybatis.SessionFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;
import org.swan.bean.MessageBean;

import java.io.InputStream;
import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

@Service
@PropertySource({"classpath:flow.properties"})
public class LocalCheckListServiceImpl implements LocalCheckListService, AfterApprovalService, InitializingBean {
    private final static Logger logger= LoggerFactory.getLogger(LocalCheckListServiceImpl.class);

    @SuppressWarnings({"unchecked", "rawtypes"})
    @Override
    public void afterPropertiesSet() throws Exception {
        Map map = flowManagement.getHandlers();
        map.put(LocalCheckListEntry.class.getName(), this);
    }

    @Value("${flow_local_check_list}")
    private String templateKey;

    @Value("${risk_danger_setCode}")
    private String riskDangerSetCode;

    @Autowired
    private FastDFSClientWrapper clientWrapper;

    @Autowired
    private Util util;

    @SuppressWarnings("deprecation")
    @Override
    public void editApproval(Audit audit) {
        List<String> idList = JSONObject.parseArray(audit.getBusinessIds(), String.class);
        try (SessionFactory factory = new SessionFactory();) {
            LocalCheckListMapper lceMapper = factory.getMapper(LocalCheckListMapper.class);
            LocalCheckListItemMapper lciMapper = factory.getMapper(LocalCheckListItemMapper.class);
            List<LocalCheckListEntry> list = lceMapper.queryByIdList("local_checklist_entry_history", idList);
            for (LocalCheckListEntry lce : list) {
                lce.setState(1);
                lce.setFstatusflag(2);
                List<LocalCheckListItem> tempList = lciMapper.queryByCheckId("local_checklist_item_history", lce.getId());
                lce.setItemList(tempList);
            }
            //保存检查表
            save(list);
            updateFstatusflag(idList, 2);
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
        }
    }


    @Override
    public void processDiscard(Audit audit) {
        // TODO Auto-generated method stub

    }


    @SuppressWarnings("deprecation")
    @Override
    public void discardApproval(Audit audit) {
        List<String> codeList = null;
        try (SessionFactory factory = new SessionFactory();) {
            List<String> idList = JSONObject.parseArray(audit.getBusinessIds(), String.class);
            LocalCheckListMapper mapper = factory.getMapper(LocalCheckListMapper.class);
            List<LocalCheckListEntry> list = mapper.queryByIdList("local_checklist_entry_history", idList);
            factory.close();
            codeList = list.stream().map(LocalCheckListEntry::getCode).collect(Collectors.toList());

        }
        if (Objects.nonNull(codeList) && !codeList.isEmpty()) {
            updateState(codeList, 0);
        }
    }

    @Autowired
    private FlowManagement flowManagement;
    @Autowired
    private DictDataService dataService;

    @SuppressWarnings({"deprecation", "rawtypes"})
    @Override
    public MessageBean<?> saveDraft(List<LocalCheckListEntry> beanList, StaffBean user) {
        MessageBean<List> msg = new MessageBean<List>();
        SessionFactory factory = new SessionFactory();
        try {
            Map checkMap = addChenk(beanList);
            int code = (int) checkMap.get("code");
            String description = (String) checkMap.get("description");
            if (code != 0) {
                msg.setCode(code);
                msg.setDescription(description);
                factory.close(false);
                return msg;
            }
            Date date = new Date();
            List<String> idList = new ArrayList<String>();
            LocalCheckListMapper lceMapper = factory.getMapper(LocalCheckListMapper.class);
            LocalCheckListItemMapper lciMapper = factory.getMapper(LocalCheckListItemMapper.class);
            for (LocalCheckListEntry lce : beanList) {
                List<LocalCheckListItem> itemList = lce.getItemList();
                if (itemList == null || itemList.size() == 0) {
                    msg.setCode(BusinessCode.MESSAGE_CODE_FAIL);
                    msg.setDescription("检查项不能为空");
                    factory.close(false);
                    return msg;
                }
                lce.setFstatusflag(0);
                lce.setHasItems(itemList.size());
                lce.setState(1);
                lce.setAddTime(date);
                lce.setAddUser(user.getCode());
                lce.setAddUserName(user.getName());
                lce.setUpdateTime(date);
                lce.setUpdateUser(user.getCode());
                lce.setUpdateUserName(user.getName());

                if (StringUtils.isEmpty(lce.getId())) {            //新增
                    String id = DefaultIdGenerator.getInstance().generateLongId();
                    lce.setId(id);
                    for (LocalCheckListItem lci : itemList) {
                        lci.setAddTime(date);
                        lci.setAddUser(user.getCode());
                        lci.setLocalChecklistEntryId(id);
                        lci.setId(DefaultIdGenerator.getInstance().generateLongId());
                    }
                    lceMapper.insert("local_checklist_entry_history", lce);
                    lciMapper.batchInsert("local_checklist_item_history", itemList);
                } else {        //修改
                    //删除检查项
                    lciMapper.deleteByCheckId("local_checklist_item_history", lce.getId());
                    for (LocalCheckListItem lci : itemList) {
                        lci.setAddTime(date);
                        lci.setAddUser(user.getCode());
                        lci.setLocalChecklistEntryId(lce.getId());
                        lci.setId(DefaultIdGenerator.getInstance().generateLongId());
                    }
                    lceMapper.update("local_checklist_entry_history", lce);
                    lciMapper.batchInsert("local_checklist_item_history", itemList);
                }
                idList.add(lce.getId());
            }
            factory.close();
            msg.setCode(0);
            msg.setDescription("保存成功");
            msg.setData(idList);
            return msg;
        } catch (Exception e) {
            if (null != factory)
                factory.close(false);
            logger.error(e.getMessage(),e);
            msg.setCode(BusinessCode.MESSAGE_CODE_EXCEPTION);
            msg.setDescription(BusinessCode.MESSAGE_DESCRIPTION_EXCEPTION);
            return msg;
        } finally {
            if (factory != null) {
                factory.close();
            }
        }
    }

    @SuppressWarnings("unchecked")
    @Override
    public MessageBean<?> submit(List<LocalCheckListEntry> beanList, StaffBean user, String title, String note, String path, String approvalCode) {
        MessageBean<?> msg = saveDraft(beanList, user);
        try {
            List<String> idList = new ArrayList<String>();
            if (msg.getData() != null) {
                idList = (List<String>) msg.getData();
            } else {
                return msg;
            }
            String corpCode = beanList.get(0).getCorpCode();
            //启动流程
            Audit audit = new Audit(title, note, user.getName(), new Date());
            audit.setId(DefaultIdGenerator.getInstance().generateLongId());
            audit.setInitiatorCode(user.getCode());
            audit.setTarget(LocalCheckListEntry.class.getName());
            audit.setTitle(title);
            audit.setDescription(note);
            audit.setTemplateKey(templateKey);
            audit.setInitiatorAccount(user.getUserid());
            audit.setSetCode(riskDangerSetCode);
            audit.setOperation(1);
            audit.setState(1);
            audit.setFlowType(1);
            audit.setFlowName(Immutable.ADD_LOCAL_CHECK_LIST_ENTRY);
            audit.setAttachment(path);
            audit.setBusinessIds(new Gson().toJson(idList));
            audit.setCorpCode(corpCode);
            Map map = new HashMap();
            map.put("approvalCode", approvalCode);
            if (!flowManagement.initFlow(user, audit, map)) {
//            	delete(idList);
                msg.setCode(BusinessCode.MESSAGE_CODE_FLOW_EXCEPTION);
                msg.setDescription(BusinessCode.MESSAGE_DESCRIPTION_FLOW_EXCEPTION);
            }
            updateFstatusflag(idList, 1);
            return msg;
        } catch (Exception e) {
            return msg;
        }
    }

    @SuppressWarnings("deprecation")
    @Override
    public MessageBean<?> discard(List<String> idList, StaffBean user, String title, String note, String approvalCode) {
        MessageBean<Boolean> msg = MessageBean.create(BusinessCode.MESSAGE_CODE_SUCCESS, BusinessCode.MESSAGE_DESCRIPTION_SUCCESS, boolean.class);
        SessionFactory factory = new SessionFactory();
        try {
            LocalCheckListMapper lceMapper = factory.getMapper(LocalCheckListMapper.class);
            LocalCheckListItemMapper lciMapper = factory.getMapper(LocalCheckListItemMapper.class);
            List<LocalCheckListEntry> lceList = lceMapper.queryByIdList("local_checklist_entry", idList);
            idList = new ArrayList<String>();
            List<LocalCheckListItem> itemList = new ArrayList<LocalCheckListItem>();
            for (LocalCheckListEntry lce : lceList) {
                String id = DefaultIdGenerator.getInstance().generateLongId();
                List<LocalCheckListItem> tempList = lciMapper.queryByCheckId("local_checklist_item", lce.getId());
                for (LocalCheckListItem item : tempList) {
                    item.setId(DefaultIdGenerator.getInstance().generateLongId());
                    item.setLocalChecklistEntryId(id);
                }
                lce.setState(0);
                lce.setId(id);
                itemList.addAll(tempList);
                idList.add(id);
            }
            if (lceList.isEmpty()) {
                msg.setCode(BusinessCode.MESSAGE_CODE_SERVICE_EXCEPTION);
                msg.setDescription(BusinessCode.MESSAGE_DESCRIPTION_SERVICE_EXCEPTION);
                factory.close(false);
                return msg;
            }
            lceMapper.batchInsert("local_checklist_entry_history", lceList);
            if (!itemList.isEmpty()) {
                lciMapper.batchInsert("local_checklist_item_history", itemList);
            }
            String corpCode = lceList.get(0).getCorpCode();
            //启动流程
            Audit audit = new Audit(title, note, user.getName(), new Date());
            audit.setId(DefaultIdGenerator.getInstance().generateLongId());
            audit.setTitle(title);
            audit.setDescription(note);
            audit.setInitiatorCode(user.getCode());
            audit.setTarget(LocalCheckListEntry.class.getName());
            audit.setTemplateKey(templateKey);
            audit.setInitiatorAccount(user.getUserid());
            audit.setSetCode(riskDangerSetCode);
            audit.setOperation(2);
            audit.setState(1);
            audit.setFlowType(1);
            audit.setFlowName(Immutable.DISCARD_LOCAL_CHECK_LIST_ENTRY);
            audit.setBusinessIds(new Gson().toJson(idList));
            audit.setCorpCode(corpCode);
            Map map = new HashMap();
            map.put("approvalCode", approvalCode);
            if (!flowManagement.initFlow(user, audit, map)) {
                msg.setCode(BusinessCode.MESSAGE_CODE_FLOW_EXCEPTION);
                msg.setDescription(BusinessCode.MESSAGE_DESCRIPTION_FLOW_EXCEPTION);
                factory.close(false);
                return msg;
            }
            factory.close();
            return msg;
        } catch (Exception e) {
            msg.setCode(BusinessCode.MESSAGE_CODE_EXCEPTION);
            msg.setDescription(BusinessCode.MESSAGE_DESCRIPTION_EXCEPTION);
            factory.close(false);
            return msg;
        }
    }

    @SuppressWarnings("deprecation")
    public void delete(List<String> idList) {
        try (SessionFactory factory = new SessionFactory()) {
            LocalCheckListMapper mapper = factory.getMapper(LocalCheckListMapper.class);
            mapper.batchDelete(idList);
            LocalCheckListItemMapper lciMapper = factory.getMapper(LocalCheckListItemMapper.class);
            for (String string : idList) {
                lciMapper.deleteByCheckId("local_checklist_item_history", string);
            }
        }
    }


    @SuppressWarnings({"rawtypes", "deprecation", "unchecked"})
    @Override
    public MessageBean<?> list(String table, String name, String corpCode, String businessTypeId, String checklistEntryTypeId, Integer state, Integer page, Integer pageSize) {
        MessageBean<DataBean> msg = MessageBean.create(BusinessCode.MESSAGE_CODE_SUCCESS, BusinessCode.MESSAGE_DESCRIPTION_SUCCESS, DataBean.class);
        Integer totalPage = null;
        Integer totalNumber = null;
        Integer start = null;
        Integer end = null;
        if (null != page && pageSize != null) {
            if (page > 0 && pageSize > 0) {
            } else {
                //第一页 10条数据
                page = 1;
                pageSize = 10;
            }
            start = (page <= 1) ? 0 : (page - 1) * pageSize;
            end = pageSize;
        }
        try (SessionFactory factory = new SessionFactory();) {
            LocalCheckListMapper lceMapper = factory.getMapper(LocalCheckListMapper.class);
            totalNumber = lceMapper.count("local_checklist_entry", name, corpCode, businessTypeId, checklistEntryTypeId, state);
            if (start != null && end != null) {
                totalPage = totalNumber / pageSize + 1;
            } else {
                totalPage = 1;
                page = totalPage;
                pageSize = totalNumber;
            }
            List<LocalCheckListEntry> list = lceMapper.list("local_checklist_entry", name, corpCode, businessTypeId, checklistEntryTypeId, state, start, end);
            LocalCheckListItemMapper lciMapper = factory.getMapper(LocalCheckListItemMapper.class);
            for (LocalCheckListEntry lce : list) {
                lce.setItemList(lciMapper.queryByCheckId("local_checklist_item", lce.getId()));
            }

            DataBean data = new DataBean();
            data.setList(list);
            data.setPageNo(page);
            data.setPageSize(pageSize);
            data.setTotalNumber(totalNumber);
            data.setTotalPage(totalPage);
            msg.setData(data);
        } catch (Exception e) {
            msg.setCode(BusinessCode.MESSAGE_CODE_EXCEPTION);
            msg.setDescription(BusinessCode.MESSAGE_DESCRIPTION_EXCEPTION);
            return msg;
        }
        return msg;
    }

    @Override
    public Integer count(String table, String businessTypeId, String name, String checklistEntryTypeId) {
        // TODO Auto-generated method stub
        return null;
    }


    @SuppressWarnings("deprecation")
    @Override
    public MessageBean<?> detailsByCode(String code) {
        MessageBean<LocalCheckListEntry> msg = MessageBean.create(BusinessCode.MESSAGE_CODE_SUCCESS, BusinessCode.MESSAGE_DESCRIPTION_SUCCESS, LocalCheckListEntry.class);
        LocalCheckListEntry lce = new LocalCheckListEntry();
        try (SessionFactory factory = new SessionFactory()) {
            LocalCheckListMapper lceMapper = factory.getMapper(LocalCheckListMapper.class);
            lce = lceMapper.queryByCode("local_checklist_entry", code);
            if (lce == null) {
                return msg;
            }
            LocalCheckListItemMapper lciMapper = factory.getMapper(LocalCheckListItemMapper.class);
            List<LocalCheckListItem> itemList = lciMapper.queryByCheckId("local_checklist_item", lce.getId());
            lce.setItemList(itemList);
            msg.setData(lce);
        } catch (Exception e) {
            // TODO: handle exception
        }
        return msg;
    }

    @Override
    public List<LocalCheckListEntry> exportList(StaffBean user, String corpCode, String name, String businessTypeId, String checklistEntryTypeId, Integer state) {
        try (SessionFactory factory = new SessionFactory()) {
            LocalCheckListMapper lceMapper = factory.getMapper(LocalCheckListMapper.class);
            List<LocalCheckListEntry> list = lceMapper.list("local_checklist_entry", name, corpCode, businessTypeId, checklistEntryTypeId, state, null, null);
            if (null != list && list.size() > 0) {
//                LocalCheckListItemMapper lciMapper = factory.getMapper(LocalCheckListItemMapper.class);
//                for (LocalCheckListEntry lce : list) {
//                    lce.setItemList(lciMapper.queryByCheckId("local_checklist_item", lce.getId()));
//                }
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                list.forEach(bean -> {
                    if (org.apache.commons.lang3.StringUtils.isNotEmpty(bean.getCorpCode())) {
                        List<DepartmentTreeBean> departmentTreeBeanList = (List<DepartmentTreeBean>) util.depttree(bean.getCorpCode(), 0).getData();
                        Map<String, String> map = departmentTreeBeanList.stream().collect(Collectors.toMap(DepartmentTreeBean::getDepartmentCode, DepartmentTreeBean::getName));
                        bean.setCorpName((departmentTreeBeanList == null || departmentTreeBeanList.size() <= 0)
                                ? null : map.get(bean.getCorpCode()));
                    }
                    if (null != bean.getAddTime()) {
                        bean.setAddTimeStr(sdf.format(bean.getAddTime()));
                    }
                });
            }
            return list;
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            return null;
        }
    }

    @SuppressWarnings("deprecation")
    @Override
    public MessageBean<?> details(String tableName, String itemTable, String id) {
        MessageBean<LocalCheckListEntry> msg = MessageBean.create(BusinessCode.MESSAGE_CODE_SUCCESS, BusinessCode.MESSAGE_DESCRIPTION_SUCCESS, LocalCheckListEntry.class);
        LocalCheckListEntry lce = new LocalCheckListEntry();
        try (SessionFactory factory = new SessionFactory()) {
            LocalCheckListMapper lceMapper = factory.getMapper(LocalCheckListMapper.class);
            lce = lceMapper.queryByid(tableName, id);
            if (lce == null) {
                return msg;
            }
            LocalCheckListItemMapper lciMapper = factory.getMapper(LocalCheckListItemMapper.class);
            List<LocalCheckListItem> itemList = lciMapper.queryByCheckId(itemTable, id);
            lce.setItemList(itemList);
        }
        msg.setData(lce);
        return msg;
    }

    @SuppressWarnings("deprecation")
    @Override
    public MessageBean<?> importExcel(StaffBean user, String code, String corpCode, String checklistEntryTypeId,
                                      String businessTypeId, String title, String note, MultipartFile file, String approvalCod) {
        MessageBean<LocalCheckListEntry> msg = MessageBean.create(BusinessCode.MESSAGE_CODE_SUCCESS, BusinessCode.MESSAGE_DESCRIPTION_SUCCESS, LocalCheckListEntry.class);
        SessionFactory factory = new SessionFactory();
        try {
            InputStream is = file.getInputStream();
            LocalCheckListEntry lce = excelAnaly(user, is);
            if (lce == null) {
                msg.setCode(32004);
                msg.setDescription("文档解析出错");
                factory.close(false);
                return msg;
            }
            if (StringUtils.isEmpty(corpCode)) {
                msg.setCode(BusinessCode.MESSAGE_CODE_SERVICE_EXCEPTION);
                msg.setDescription(BusinessCode.MESSAGE_DESCRIPTION_SERVICE_EXCEPTION);
                factory.close(false);
                return msg;
            }
            if (StringUtils.isEmpty(code)) {
                if (StringUtils.isEmpty(businessTypeId) || StringUtils.isEmpty(checklistEntryTypeId)) {
                    msg.setCode(BusinessCode.MESSAGE_CODE_SERVICE_EXCEPTION);
                    msg.setDescription("新增检查表必须选择业态和检查表类型");
                    factory.close(false);
                    return msg;
                }
                lce.setBusinessTypeId(businessTypeId);
                lce.setChecklistEntryTypeId(checklistEntryTypeId);
            } else {
                LocalCheckListMapper lceMapper = factory.getMapper(LocalCheckListMapper.class);
                LocalCheckListEntry oldlce = lceMapper.queryByCode("local_checklist_entry", code);
                if (oldlce == null) {
                    factory.close(false);
                    msg.setCode(BusinessCode.MESSAGE_CODE_SERVICE_EXCEPTION);
                    msg.setDescription("检查表编码错误");
                    return msg;
                }
                lce.setBusinessTypeId(oldlce.getBusinessTypeId());
                lce.setChecklistEntryTypeId(oldlce.getChecklistEntryTypeId());
            }
            lce.setCode(code);
            lce.setCorpCode(corpCode);
            String url = clientWrapper.uploadFile(file);
            String fileName = file.getOriginalFilename();
            String path = url + "#" + fileName;

            List<LocalCheckListEntry> beanList = new ArrayList<LocalCheckListEntry>();
            beanList.add(lce);
            factory.close();
            return submit(beanList, user, title, note, path, approvalCod);
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            factory.close(false);
            msg.setCode(BusinessCode.MESSAGE_CODE_EXCEPTION);
            msg.setDescription("文档不规范");
            return msg;
        } finally {
            if (factory != null) {
                factory.close();
            }
        }
    }


    @SuppressWarnings("resource")
    private LocalCheckListEntry excelAnaly(StaffBean user, InputStream is) throws Exception {
        XSSFWorkbook workbook = new XSSFWorkbook(is);
        XSSFSheet sheet = workbook.getSheetAt(0);
        if (sheet == null) {
            return null;
        }
        Cell checkEntryNameCell = sheet.getRow(0).getCell(0);
        // 上传的检查表名称为空直接返回
        String name = getCellValue(checkEntryNameCell);
        if (StringUtils.isEmpty(name)) {
            return null;
        }
        LocalCheckListEntry lce = new LocalCheckListEntry();
        lce.setName(name);
        lce.setAddTime(new Date());
        lce.setAddUser(user.getCode());
        lce.setAddUserName(user.getName());
        lce.setUpdateUser(user.getCode());
        lce.setUpdateUserName(user.getName());
        List<LocalCheckListItem> items = new ArrayList<LocalCheckListItem>();
        // 去获取检查项
        for (int rowNum = 7; rowNum <= sheet.getLastRowNum(); ) {
            Row row = sheet.getRow(rowNum);
            if (row == null) {
                continue;
            }
            String keyword = getCellValue(row.getCell(0));
            String itemIndex = getCellValue(row.getCell(1));
            String itemName = getCellValue(row.getCell(3));
            LocalCheckListItem lci = new LocalCheckListItem();
            if (!StringUtils.isEmpty(itemIndex)) {
                double d = Double.parseDouble(itemIndex);
                lci.setItemIndex(Double.valueOf(d).intValue());
            }
            lci.setName(itemName);
            lci.setKeyword(keyword);
            items.add(lci);
            rowNum++;
        }
        lce.setItemList(items);

        return lce;
    }

   /* private CellRangeAddress getCellRange(List<CellRangeAddress> listCombineCell, Cell cell) {
        int firstC = 0, lastC = 0, firstR = 0, lastR = 0;
        for (CellRangeAddress ca : listCombineCell) {
            // 获得合并单元格的起始行, 结束行, 起始列, 结束列
            firstC = ca.getFirstColumn();
            lastC = ca.getLastColumn();
            firstR = ca.getFirstRow();
            lastR = ca.getLastRow();
            if (cell.getRowIndex() >= firstR && cell.getRowIndex() <= lastR) {
                if (cell.getColumnIndex() >= firstC && cell.getColumnIndex() <= lastC) {
                    return ca;
                }
            }
        }
        return null;
    }*/


    /**
     * 获取单元格的值
     *
     * @param cell
     * @return
     */
    @SuppressWarnings("deprecation")
    public String getCellValue(Cell cell) {
        if (cell == null)
            return "";
        if (cell.getCellTypeEnum() == CellType.STRING) {
            return cell.getStringCellValue();
        } else if (cell.getCellTypeEnum() == CellType.BOOLEAN) {
            return String.valueOf(cell.getBooleanCellValue());
        } else if (cell.getCellTypeEnum() == CellType.FORMULA) {
            return cell.getCellFormula();
        } else if (cell.getCellTypeEnum() == CellType.NUMERIC) {
            return String.valueOf(cell.getNumericCellValue());
        } else {
            return "";
        }
    }

    /**
     * 合并单元格处理,获取合并行
     *
     * @param sheet
     * @return List<CellRangeAddress>
     */
    public List<CellRangeAddress> getCombineCell(XSSFSheet sheet) {
        List<CellRangeAddress> list = new ArrayList<CellRangeAddress>();
        // 获得一个 sheet 中合并单元格的数量
        int sheetmergerCount = sheet.getNumMergedRegions();
        // 遍历所有的合并单元格
        for (int i = 0; i < sheetmergerCount; i++) {
            // 获得合并单元格保存进list中
            CellRangeAddress ca = sheet.getMergedRegion(i);
            list.add(ca);
        }
        return list;
    }

    @SuppressWarnings({"deprecation", "rawtypes"})
    @Override
    public MessageBean<?> getDraftList(StaffBean user, String corpCode) {
        MessageBean<List> msg = MessageBean.create(BusinessCode.MESSAGE_CODE_SUCCESS, BusinessCode.MESSAGE_DESCRIPTION_SUCCESS, List.class);
        try (SessionFactory factory = new SessionFactory();) {
            LocalCheckListMapper lceMapper = factory.getMapper(LocalCheckListMapper.class);
            LocalCheckListItemMapper lciMapper = factory.getMapper(LocalCheckListItemMapper.class);
            List<LocalCheckListEntry> list = lceMapper.getDraftList(user.getCode(), corpCode);
            for (LocalCheckListEntry lce : list) {
                lce.setItemList(lciMapper.queryByCheckId("local_checklist_item_history", lce.getId()));
            }
            msg.setData(list);
        } catch (Exception e) {
            msg.setCode(BusinessCode.MESSAGE_CODE_EXCEPTION);
            msg.setDescription(BusinessCode.MESSAGE_DESCRIPTION_EXCEPTION);
        }
        return msg;

    }

    @SuppressWarnings({"rawtypes", "unchecked"})
    private Map addChenk(List<LocalCheckListEntry> beanList) {
        Map map = new HashMap();
        for (LocalCheckListEntry lce : beanList) {
            if (lce == null) {
                map.put("code", 32001);
                map.put("description", "未填写检查表无法保存");
                return map;
            }
            List<LocalCheckListItem> lciList = lce.getItemList();
            if (lciList == null) {
                map.put("code", 32001);
                map.put("description", "未填写检查项无法保存");
                return map;
            }
            if (StringUtils.isEmpty(lce.getName())) {
                map.put("code", 32001);
                map.put("description", "检查表名称不能为空");
                return map;
            }
            if (StringUtils.isEmpty(lce.getChecklistEntryTypeId())) {
                map.put("code", 32001);
                map.put("description", "检查表类型不能为空");
                return map;
            }
            if (StringUtils.isEmpty(lce.getCorpCode())) {
                map.put("code", 32001);
                map.put("description", "公司不能为空");
                return map;
            }
            for (LocalCheckListItem item : lciList) {
                if (StringUtils.isEmpty(item.getName())) {
                    map.put("code", 32001);
                    map.put("description", "检查表名称不能为空");
                    return map;
                }
               /* if (StringUtils.isEmpty(item.getKeyword())) {
                    map.put("code", 32001);
                    map.put("description", "检查项类别不能为空");
                    return map;
                }*/
            }
        }
        map.put("code", 0);
        map.put("description", "校验成功");
        return map;
    }

    @SuppressWarnings({"deprecation"})
    private void updateState(List<String> codeList, int state) {
        try (SessionFactory factory = new SessionFactory();) {
            LocalCheckListMapper mapper = factory.getMapper(LocalCheckListMapper.class);
            mapper.updateState(codeList, state);
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
        }
    }


    @SuppressWarnings("deprecation")
    private void updateFstatusflag(List<String> idList, int fstatusflag) {
        try (SessionFactory factory = new SessionFactory();) {
            LocalCheckListMapper mapper = factory.getMapper(LocalCheckListMapper.class);
            mapper.updateFstatusflag(idList, fstatusflag);
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
        }
    }

    private String generateCode(SessionFactory factory, LocalCheckListEntry lce) {
        String convert = "";
        CorpManagementMapper corpMapper = factory.getMapper(CorpManagementMapper.class);
        CorpBean corpBean = corpMapper.get(lce.getCorpCode());
        if (corpBean == null) {
            convert = "#####";
            return convert;
        }
        convert = corpBean.getShortCode();
        if (StringUtils.isEmpty(convert)) {
            convert = "#####";
            return convert;
        }
        StringBuilder sb = new StringBuilder();
        LocalCheckListMapper mapper = factory.getMapper(LocalCheckListMapper.class);
        String businessValue = "";
        String hazardValue = "";
        DictData businessType = dataService.queryOne(lce.getBusinessTypeId()).getData();
        if (businessType != null) {
            businessValue = businessType.getDictValue();
        }
        DictData hazardType = dataService.queryOne(lce.getChecklistEntryTypeId()).getData();
        if (hazardType != null) {
            hazardValue = hazardType.getDictValue();
        }
        Integer count = mapper.count("local_checklist_entry", null, lce.getCorpCode(), lce.getBusinessTypeId(), lce.getChecklistEntryTypeId(), null);
        count++;
        NumberFormat nf = NumberFormat.getInstance();
        nf.setGroupingUsed(false);
        nf.setMaximumIntegerDigits(3); // 设置最大整数位数
        nf.setMinimumIntegerDigits(3); // 设置最小整数位数
        sb.append(businessValue).append(hazardValue).append(nf.format(count)).append("-").append(convert);
        return sb.toString();
    }

    @SuppressWarnings("deprecation")
    public void save(List<LocalCheckListEntry> beanList) {
        try (SessionFactory factory = new SessionFactory();) {
            LocalCheckListMapper lceMapper = factory.getMapper(LocalCheckListMapper.class);
            LocalCheckListItemMapper lciMapper = factory.getMapper(LocalCheckListItemMapper.class);
            for (LocalCheckListEntry lce : beanList) {
                String oldId = lce.getId();
                List<LocalCheckListItem> itemList = lce.getItemList();
                lce.setState(1);//发布状态
                Date date = new Date();
                if (StringUtils.isEmpty(lce.getCode())) {
                    //新增
                    String id = DefaultIdGenerator.getInstance().generateLongId();
                    lce.setAddTime(date);
                    lce.setCode(generateCode(factory, lce));
                    lce.setId(id);
                    for (LocalCheckListItem item : itemList) {
                        item.setId(DefaultIdGenerator.getInstance().generateLongId());
                        item.setLocalChecklistEntryId(id);
                        item.setAddTime(date);
                    }
                    lce.setHasItems(itemList.size());
                    lceMapper.insert("local_checklist_entry", lce);
                    lceMapper.updateCode(oldId, lce.getCode());
                } else {
                    String code = lce.getCode();
                    LocalCheckListEntry lceOld = lceMapper.queryByCode("local_checklist_entry", code);
                    if (lceOld == null) {//新增
                        lce.setId(DefaultIdGenerator.getInstance().generateLongId());
                        lce.setAddTime(date);
                        lce.setCode(generateCode(factory, lce));
                        for (LocalCheckListItem item : itemList) {
                            item.setId(DefaultIdGenerator.getInstance().generateLongId());
                            item.setLocalChecklistEntryId(lce.getId());
                            item.setAddTime(date);
                        }
                        lce.setHasItems(itemList.size());
                        lceMapper.insert("local_checklist_entry", lce);
                        lceMapper.updateCode(oldId, lce.getCode());
                    } else {//修改
                        lciMapper.deleteByCheckId("local_checklist_item", lceOld.getId());
                        lce.setId(lceOld.getId());
                        lce.setUpdateTime(date);
                        for (LocalCheckListItem item : itemList) {
                            item.setId(DefaultIdGenerator.getInstance().generateLongId());
                            item.setLocalChecklistEntryId(lce.getId());
                            item.setAddTime(date);
                        }
                        lce.setHasItems(itemList.size());
                        lceMapper.update("local_checklist_entry", lce);
                    }
                }
                lciMapper.batchInsert("local_checklist_item", itemList);
            }
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
        }
    }

    @SuppressWarnings({"deprecation", "rawtypes"})
    @Override
    public MessageBean<?> getHistoryList(String code) {
        MessageBean<List> msg = MessageBean.create(0, "success", List.class);
        try (SessionFactory factory = new SessionFactory()) {
            LocalCheckListMapper lceMapper = factory.getMapper(LocalCheckListMapper.class);
            LocalCheckListItemMapper lciMapper = factory.getMapper(LocalCheckListItemMapper.class);
            List<LocalCheckListEntry> list = lceMapper.queryHstory(code);
            for (LocalCheckListEntry lce : list) {
                lce.setItemList(lciMapper.queryByCheckId("local_checklist_item_history", lce.getId()));
            }
            msg.setData(list);
        } catch (Exception e) {
            msg.setCode(BusinessCode.MESSAGE_CODE_EXCEPTION);
            msg.setDescription(BusinessCode.MESSAGE_DESCRIPTION_EXCEPTION);
            return msg;
        }
        return msg;
    }

    @SuppressWarnings({"deprecation", "rawtypes"})
    @Override
    public MessageBean<?> getProcessData(String ids) {
        MessageBean<List> msg = MessageBean.create(0, "success", List.class);
        try (SessionFactory factory = new SessionFactory();) {
            Map<String, String> corpMap = new HashMap<String, String>();
            List<String> idList = JSONObject.parseArray(ids, String.class);
            LocalCheckListMapper lceMapper = factory.getMapper(LocalCheckListMapper.class);
            LocalCheckListItemMapper lciMapper = factory.getMapper(LocalCheckListItemMapper.class);
            List<LocalCheckListEntry> list = lceMapper.queryByIdList("local_checklist_entry_history", idList);
            for (LocalCheckListEntry lce : list) {
                lce.setItemList(lciMapper.queryByCheckId("local_checklist_item_history", lce.getId()));
                String corpName = corpMap.get(lce.getCorpCode());
                if (corpName == null) {
                    CorpBean corpBean = factory.getMapper(CorpManagementMapper.class).get(lce.getCorpCode());
                    if (corpBean != null) {
                        corpName = corpBean.getCorpName();
                        corpMap.put(lce.getCorpCode(), corpName);
                    }
                }
                lce.setCorpName(corpName);
            }
            msg.setData(list);
        } catch (Exception e) {
            msg.setCode(BusinessCode.MESSAGE_CODE_EXCEPTION);
            msg.setDescription(BusinessCode.MESSAGE_DESCRIPTION_EXCEPTION);
            return msg;
        }
        return msg;
    }

    @SuppressWarnings("deprecation")
    @Override
    public MessageBean<?> deleteDraft(String id) {
        MessageBean<?> msg = MessageBean.create(0, "success", void.class);
        SessionFactory factory = new SessionFactory();
        try {
            LocalCheckListMapper lceMapper = factory.getMapper(LocalCheckListMapper.class);
            LocalCheckListItemMapper lciMapper = factory.getMapper(LocalCheckListItemMapper.class);
            lceMapper.deleteDraft(id);
            lciMapper.deleteDraft(id);
            factory.close();
        } catch (Exception e) {
            factory.close(false);
            msg.setCode(BusinessCode.MESSAGE_CODE_EXCEPTION);
            msg.setDescription(BusinessCode.MESSAGE_DESCRIPTION_EXCEPTION);
            return msg;
        }
        return msg;
    }


    @Override
    public void reject(Audit audit, List<String> userIdList) {
        // TODO 流程驳回操作
    }

    @Override
    public void passApproval(Integer operation, Audit audit) {
        // TODO 流程提交成功操作
    }

}
